package 力扣._6939_数组中最大对数和;

import java.util.*;

public class Solution {

    //获取最大位
    int maxwei(int num) {
        int max = 0;
        while (num > 0) {
            max = Math.max(max, num % 10);
            num /= 10;
        }
        return max;
    }

    void reverse(int[] nums) {
        int t;
        for (int i = 0, j = nums.length - 1; i < j; i++, j--) {
            t = nums[i];
            nums[i] = nums[j];
            nums[j] = t;
        }
    }

    public int maxSum(int[] nums) {
        Arrays.sort(nums);
        reverse(nums);
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int num : nums) {
            List<Integer> numlist = map.getOrDefault(maxwei(num), new ArrayList<>());
            numlist.add(num);
            map.put(maxwei(num), numlist);
        }

        int max = -1;
        Set<Integer> keySet = map.keySet();
        for (Integer key : keySet) {
            List<Integer> list = map.get(key);
            if (list.size() > 1) {
                max = Math.max(max, list.get(0) + list.get(1));
            }
        }
        return max;
    }
}
